package com.asset.salesforce.service;


import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.Sha256CredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.aspectj.lang.annotation.Aspect;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.asset.salesforce.dao.UserShiroDaoImpl;
import com.asset.salesforce.domain.Role;
import com.asset.salesforce.domain.User;
@Service
@Transactional(readOnly=false)
//@Component
public class SampleRealm extends AuthorizingRealm {

	public UserShiroDaoImpl userShiroDaoImpl=null;
 
    public UserShiroDaoImpl getUserShiroDaoImpl() {
		return userShiroDaoImpl;
	}


    @Autowired
	public void setUserShiroDaoImpl(UserShiroDaoImpl userShiroDaoImpl) {
		this.userShiroDaoImpl = userShiroDaoImpl;
	}



	public SampleRealm() {
        setName("SampleRealm"); //This name must match the name in the User class's getPrincipals() method
        setCredentialsMatcher(new Sha256CredentialsMatcher());
    }

   

    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
        User user = new User();
         user = userShiroDaoImpl.findUser(token.getUsername());
         System.out.println(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
        if( user != null ) {
            return new SimpleAuthenticationInfo(user.getId(), user.getPassword(), getName());
        } else {
            return null;
        }
    }


    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        Integer userId = (Integer) principals.fromRealm(getName()).iterator().next();
        User user = userShiroDaoImpl.getUserById(userId);
        if( user != null ) {
            SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
            for( Role role : user.getRoles() ) {
                info.addRole(role.getName());
                info.addStringPermissions( role.getPermissions() );
            }
            return info;
        } else {
            return null;
        }
    }

}

